{% extends "admin/layout.html" %}
{% set active_page = "system_config" %}

{% block content %}
<div class="container-fluid">
    <h2 class="mb-4">系统设置</h2>

    <div class="card shadow-sm">
        <div class="card-header">
            <h5 class="mb-0">企业微信配置</h5>
        </div>
        <div class="card-body">
            <form action="{{ url_for('wxwork.system_config') }}" method="POST">
                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                <div class="mb-3">
                    <label class="form-label" for="corp_id">企业ID (CorpID)</label>
                    <input class="form-control" id="corp_id" name="corp_id" required
                           type="text" value="{{ config.corp_id if config else '' }}">
                    <div class="form-text">在"我的企业"->"企业信息"中查看</div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="corp_secret">通讯录Secret</label>
                        <input class="form-control" id="corp_secret" name="corp_secret" required
                               type="password" value="{{ config.corp_secret if config else '' }}">
                        <div class="form-text">用于同步组织架构</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="agent_id">应用AgentID</label>
                        <input class="form-control" id="agent_id" name="agent_id" type="text"
                               value="{{ config.agent_id if config else '' }}">
                        <div class="form-text">可选，用于消息推送</div>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">当前Token状态</label>
                    <div class="alert alert-info">
                        {% if config and config.access_token %}
                        <p class="mb-1">Token: {{ config.access_token[:10] }}...{{ config.access_token[-10:] }}</p>
                        <p class="mb-0">有效期至: {{ config.token_expires.strftime('%Y-%m-%d %H:%M:%S') }}</p>
                        {% else %}
                        <p class="mb-0">未获取Token</p>
                        {% endif %}
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">扫码登录设置</label>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" id="loginEnabled" name="loginEnabled" type="checkbox"
                               {{ 'checked' if config.login_enabled else '' }}>
                        <input name="loginEnabled" type="hidden" value="on">
                        <label class="form-check-label" for="loginEnabled">启用前台扫码登录</label>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="loginRedirectUri">登录回调URL</label>
                        <input class="form-control" id="loginRedirectUri" name="loginRedirectUri"
                               type="text" value="{{ config.login_redirect_uri if config.login_redirect_uri else '' }}">
                        <div class="form-text">可选，默认使用系统自动生成的回调地址</div>
                    </div>
                </div>

                <div class="d-flex justify-content-end">
                    <!-- ✅ 修复点1: 添加刷新Token功能 -->
                    <button class="btn btn-secondary me-2" id="refreshTokenBtn" type="button">
                        <i class="fas fa-sync-alt me-1"></i> 刷新Token
                    </button>
                    <button class="btn btn-primary" type="submit">
                        <i class="fas fa-save me-1"></i> 保存配置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm mt-4">
        <div class="card-header">
            <h5 class="mb-0">同步设置</h5>
        </div>
        <div class="card-body">
            <!-- ✅ 修复点2: 将同步设置合并到主表单中 -->
            <div class="mb-3">
                <label class="form-label">自动同步</label>
                <div class="form-check form-switch">
                    <input class="form-check-input" id="autoSync" name="autoSyn" type="checkbox"
                           {{ 'checked' if config.auto_sync else '' }}>
                    <input name="autoSync" type="hidden" value="on">
                    <label class="form-check-label" for="autoSync">启用自动同步</label>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label" for="syncInterval">同步频率</label>
                    <select class="form-select" id="syncInterval" name="syncInterval">
                        <option value="1" {{
                        'selected' if config.sync_interval == 1 else '' }}>每小时</option>
                        <option value="3" {{
                        'selected' if config.sync_interval == 3 else '' }}>每3小时</option>
                        <option value="6" {{
                        'selected' if config.sync_interval == 6 else '' }}>每6小时</option>
                        <option value="12" {{
                        'selected' if config.sync_interval == 12 else '' }}>每12小时</option>
                        <option value="24" {{
                        'selected' if config.sync_interval == 24 else '' }}>每天</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label" for="nextSync">下次同步时间</label>
                    <input class="form-control" id="nextSync" readonly
                           type="text"
                           value="{{ next_sync_time.strftime('%Y-%m-%d %H:%M:%S') if next_sync_time else '未设置' }}">
                </div>
            </div>

            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                启用自动同步后，系统将按照设定的频率自动同步组织架构，无需手动操作。
            </div>
        </div>
    </div>
</div>

<!-- ✅ 修复点3: 添加刷新Token的JavaScript代码 -->
<script>
    document.getElementById('refreshTokenBtn').addEventListener('click', function () {
        fetch('{{ url_for("wxwork.refresh_token") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新Token显示
                    const tokenElement = document.querySelector('.alert-info p:first-child');
                    const expiresElement = document.querySelector('.alert-info p:last-child');

                    tokenElement.textContent = `Token: ${data.token}`;
                    expiresElement.textContent = `有效期至: ${data.expires}`;

                    alert('Token刷新成功！');
                } else {
                    alert('刷新Token失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('请求失败，请检查控制台日志');
            });
    });
</script>
{% endblock %}